package com.service.login.controller;

import com.service.config.annotation.LoginUser;
import com.service.config.utils.*;
import com.service.login.entity.ServiceInfo;

import com.service.login.service.ServiceInfoService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

import static com.service.config.constant.Constant.*;


/**
 * (ServiceInfo)表控制层
 *
 * @author makejava
 * @since 2021-03-31 14:37:11
 */
@CrossOrigin
@RestController
@RequestMapping("serviceInfo")
@Api(value = "服务信息")
public class ServiceInfoController {
    /**
     * 服务对象
     */
    @Resource
    private ServiceInfoService serviceInfoService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户获取已添加的服务
     *
     * @param
     * @return
     */
    @GetMapping(value = "getAllServices",produces="application/json")
    @ApiOperation(value = "获取服务")
    @ResponseBody
    public Result getAllServices() throws Exception {
        if (redisUtil.exist(SERVICE_INFO)) {
            Set<String> values = redisUtil.setValues(SERVICE_INFO);
            List<ServiceInfo> serviceInfos = ModelMapperUtil.strictMapList(values, ServiceInfo.class);
            return Result.ok().setData(serviceInfos);
        }
        return Result.ok().setData(serviceInfoService.queryAll());
    }
    /**
     * 增加服务
     *
     * @param
     * @return
     */
    @GetMapping(value = "addService",produces="application/json")
    @ApiOperation(value = "增加服务")
    @ResponseBody
    public Result addService(@RequestHeader(value = "cloud-Auth-Token") String cloudAuthToken, @RequestBody ServiceInfo serviceInfo) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) {
                serviceInfo.setId(IdUtil.getStringId());
                serviceInfoService.insert(serviceInfo);
                List<ServiceInfo> serviceInfos = serviceInfoService.queryAll();
                serviceInfos.stream().forEach(serviceInfo1 -> {
                    try {
                        redisUtil.add(SERVICE_INFO, JsonXMLUtils.obj2json(serviceInfo1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }else {
                return Result.failure(USERNAME_Off_SITE,usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN,"用户未登录");
    }
}
